<template>
  <div class="edit-menu">
    <a-modal
      title="APP更新管理"
      width="900px"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="requestSpinning" tip="正在加载数据中...">
        <a-form :form="form">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="APPID">
                <a-input
                  disabled
                  v-decorator="[
                    'appid',
                    { initialValue: '__UNI__346D43F', rules: [{ required: true, message: '请输入APPID' }] },
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="应用名称">
                <a-input
                  disabled
                  v-decorator="[
                    'name',
                    { initialValue: '遵义鑫汇APP', rules: [{ required: true, message: '请输入应用名称' }] },
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="更新标题">
                <a-input
                  placeholder="请输入更新标题"
                  v-decorator="['title', { rules: [{ required: true, message: '请输入更新标题' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="当前版本号" extra="示例：1.0.0">
                <a-input
                  placeholder="请输入当前版本号"
                  v-decorator="['version', { rules: [{ required: true, message: '请输入当前版本号' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="更新内容">
                <a-textarea
                  :autoSize="{ minRows: 2, maxRows: 4 }"
                  placeholder="请输入更新内容"
                  v-decorator="['contents', { rules: [{ required: true, message: '请输入更新内容' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="更新平台">
                <a-select
                  placeholder="请选择更新平台"
                  v-decorator="['platform', { rules: [{ required: true, message: '请选择更新平台' }] }]"
                  :options="platformOptions"
                  @change="handleTypeChange($event, form.getFieldValue('type'))"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="安装包类型">
                <a-select
                  placeholder="请选择安装包类型"
                  v-decorator="['type', { rules: [{ required: true, message: '请选择安装包类型' }] }]"
                  :options="typeOptions"
                  @change="handleTypeChange(form.getFieldValue('platform'), $event)"
                />
              </a-form-item>
            </a-col>
            <a-col v-show="form.getFieldValue('type') === '2'" :span="12">
              <a-form-item label="请选择最低版本">
                <a-select
                  placeholder="请选择wgt更新最低版本"
                  v-decorator="[
                    'minversion',
                    {
                      preserve: true,
                      rules: [{ required: form.getFieldValue('type') === '2', message: '请选择wgt更新最低版本' }],
                    },
                  ]"
                  :options="wgtOptions"
                />
              </a-form-item>
            </a-col>
            <a-col
              :span="12"
              v-show="['2', '3'].includes(form.getFieldValue('platform')) && form.getFieldValue('type') !== '2'"
            >
              <a-form-item label="APPSTORE地址">
                <a-input
                  placeholder="请输入APPSTORE地址"
                  v-decorator="[
                    'iosUrl',
                    {
                      rules: [
                        {
                          initialValue: '',
                          required:
                            ['2', '3'].includes(form.getFieldValue('platform')) && form.getFieldValue('type') !== '2',
                          message: '请输入APPSTORE地址',
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="!(form.getFieldValue('platform') === '2' && form.getFieldValue('type') === '1')">
            <a-col :span="24">
              <a-form-item label="上传">
                <a-upload
                  name="file"
                  :file-list="fileList"
                  :multiple="false"
                  :action="action"
                  :headers="headers"
                  :remove="handleUploadRemove"
                  @change="handleUploadChange"
                >
                  <a-button type="primary"> <a-icon type="upload" /> 点击上传</a-button>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="下载地址">
                <a-input
                  placeholder="请输入下载地址"
                  v-decorator="[
                    'url',
                    {
                      initialValue: '',
                      rules: [
                        {
                          required: !(form.getFieldValue('platform') === '2' && form.getFieldValue('type') === '1'),
                          message: '请输入下载地址',
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="是否上线发行">
                <a-switch
                  v-decorator="[
                    'stable_publish',
                    {
                      initialValue: true,
                      valuePropName: 'checked',
                      rules: [{ required: true, message: '请选择是否上线发行' }],
                    },
                  ]"
                ></a-switch>
              </a-form-item>
            </a-col>
            <a-col :span="8" v-show="form.getFieldValue('type') === '2'">
              <a-form-item label="是否默认更新">
                <a-switch
                  v-decorator="[
                    'is_silently',
                    {
                      initialValue: false,
                      valuePropName: 'checked',
                    },
                  ]"
                ></a-switch>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="是否强制更新">
                <a-switch
                  v-decorator="[
                    'is_mandatory',
                    {
                      initialValue: false,
                      valuePropName: 'checked',
                    },
                  ]"
                ></a-switch>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getVersionOptions, addUpdateAppModel, editUpdateAppModel } from '@/api/application'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import pick from 'lodash.pick'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      action: process.env.VUE_APP_API_BASE_URL + '/api/uploadpictures/UploadPicturese',
      headers: {
        Authorization: storage.get(ACCESS_TOKEN),
        GF: this.$store.getters.userid
      },
      fileList: [],
      platformOptions: [
        {
          label: 'Android',
          value: '1'
        },
        {
          label: 'iOS',
          value: '2'
        },
        {
          label: 'Android,iOS',
          value: '3'
        }
      ],
      typeOptions: [
        {
          label: 'native_app',
          value: '1'
        },
        {
          label: 'wgt',
          value: '2'
        }
      ],
      wgtOptions: [],
      confirmLoading: false,
      requestSpinning: false,
      form: this.$form.createForm(this, { name: 'user' })
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler (n) {
        if (n) {
          this.fetchData()
        }
      }
    }
  },
  methods: {
    fetchData () {
      if (!this.$isEmpty(this.propsData)) {
        const values = pick(this.propsData, [
          // 'appid',
          // 'name',
          'title',
          'contents',
          'platform',
          'type',
          'version',
          'url',
          'stable_publish',
          'is_silently',
          'is_mandatory'
        ])
        values.platform = values.platform.toString()
        values.type = values.type.toString()
        this.$nextTick(() => {
          this.form.setFieldsValue(
            Object.assign(values, {
              iosUrl: this.propsData.spare2
            })
          )
        })
      }
    },
    handleUploadRemove () {
      this.form.setFieldsValue({
        url: ''
      })
      return true
    },
    handleUploadChange (info) {
      let fileList = [...info.fileList]
      fileList = fileList.slice(-1)
      fileList = fileList.map((file) => {
        if (file.response) {
          const url = process.env.VUE_APP_API_BASE_URL + file.response.data[0]
          this.form.setFieldsValue({
            url
          })
          file.url = url
        }
        return file
      })
      this.fileList = fileList
    },
    handleTypeChange (platform, type) {
      type = parseInt(type)
      if (type === 2) {
        getVersionOptions({
          platform: parseInt(platform)
        }).then((res) => {
          const arr = ['Android', 'IOS', 'ALL']
          this.wgtOptions = res.data.map((e) => {
            return {
              value: e.ID,
              label: e.name + ' For ' + arr[parseInt(e.value) - 1]
            }
          })
        })
      }
      this.wgtOptions = []
      this.form.setFieldsValue({
        url: '',
        iosUrl: ''
      })
    },
    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      const isEdit = !this.$isEmpty(this.propsData)
      validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          values = Object.entries(values).reduce(
            (acc, [key, value]) => ({
              ...acc,
              [key]: typeof value === 'undefined' ? '' : value
            }),
            {}
          )
          if (isEdit) {
            values.ID = parseInt(this.propsData.ID)
            values.spare2 = values.iosUrl
            delete values.iosUrl
          }
          const request = isEdit ? editUpdateAppModel : addUpdateAppModel
          request({
            list: values
          })
            .then((res) => {
              const { code, msg } = res
              if (code === 200) {
                this.$message.success('提交成功')
                this.$emit('success', isEdit)
                this.handleCancel()
              } else {
                this.$message.error(msg || '提交失败')
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.$emit('update:visible', false)
    }
  }
}
</script>
